package view.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import org.androidannotations.annotations.EView;

import activity.myrecyclerview.R;

/**
 * Created by Administrator on 2016/1/23.
 */
@EView
public class CircleImage extends ImageView {

    private Paint mPaint,circlepaint;
    private Matrix mMatrix;
    private Bitmap bitmap;
    private BitmapShader mBitmapShader;
    private int mRadius=100;
    private int mw=10;//外圆的宽度
    private int bitmapsize;//正方形图片的长宽
    private int outcolor;

    public CircleImage(Context context) {
        this(context, null);
    }

    public CircleImage(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.circleImg);
        mRadius = ta.getInteger(R.styleable.circleImg_radius, 50);
        outcolor=ta.getColor(R.styleable.circleImg_outcolor,R.color.gray_white);
        mw=ta.getInteger(R.styleable.circleImg_outweight,10);
        ta.recycle();
    }

    public void init() {

        mPaint=new Paint();
        mPaint.setAntiAlias(true);
        mMatrix=new Matrix();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Drawable drawable=getDrawable();
        Bitmap bt=((BitmapDrawable) drawable).getBitmap();
        int w=bt.getWidth();int h=bt.getHeight();
        int rx=0,ry=0;
        if(w>h){
            rx=(w-h)/2;
        }else{
            ry=(h-w)/2;
        }
        bitmapsize=w<h?w:h;
        bitmap=Bitmap.createBitmap(bt,rx,ry,bitmapsize,bitmapsize,null,false);
        setMeasuredDimension((mRadius+mw) * 2, (mRadius+mw) * 2);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        circlepaint=new Paint();
        circlepaint.setAntiAlias(true);
        circlepaint.setColor(outcolor);
        circlepaint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(mRadius+mw,mRadius+mw,mRadius+mw,circlepaint);

        mBitmapShader=new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        float scale=(float)(2*mRadius)/(float)bitmapsize;
        mMatrix.setScale(scale, scale);
        mBitmapShader.setLocalMatrix(mMatrix);
        mPaint.setShader(mBitmapShader);
        canvas.drawCircle(mRadius+mw, mRadius+mw, mRadius, mPaint);

    }

}
